<?php

namespace app\service;

use app\model\Setting as SettingModel;
use think\facade\Cache;

class SettingService
{
    protected $model;

    public function __construct(){
        $this->model = app()->make(SettingModel::class);
    }

    /**
     * @return SettingModel[]|array|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getSetting()
    {
        $settingStr = Cache::get('setting');
        if (!empty($settingStr)) {
            return json_decode($settingStr, true);
        }
        $setting = $this->model->field('id, name, value')->select();;
        $settingData = array();
        foreach ($setting as $key=>$item) {
            $settingData['setting'.ucfirst($item->name)] = $item->value;
        }
        Cache::set('setting', json_encode($settingData), 3600);
        return $settingData;
    }

    /**
     * 获取单个配置
     *
     * @param $key
     * @return SettingModel|mixed|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getOneSetting($key) {
        $settings = $this->getSetting();
        $settingKey ='setting' . ucfirst($key);
        if (empty($settings) || empty($settings[$settingKey])) {
            return '';
        }
        return $settings[$settingKey];
    }
}